<template>
  <div>
  <el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>用户管理</el-breadcrumb-item>
  <el-breadcrumb-item>用户列表</el-breadcrumb-item>
</el-breadcrumb>
<!-- 卡片 -->

<el-card class="box-card">

  <el-input clearable @clear="getUserlist" placeholder="请输入内容"  type="text" v-model="queryInfo.query" class="searchBar">

    <el-button slot="append" icon="el-icon-search" @click="getUserlist" class="addBut"></el-button>
  </el-input>

  <el-button type="primary" class="addBut" @click="dialogVisible=true">添加用户</el-button>


<!-- 用户信息 -->
  <el-table border stripe
      :data="userslist"
      style="width: 100%">
  <el-table-column type="index"></el-table-column>
      <el-table-column
        prop="username"
        label="姓名">
      </el-table-column>
      <el-table-column
        prop="email"
        label="邮箱">
      </el-table-column>
      <el-table-column
        prop="mobile"
        label="手机"
        width="180">
      </el-table-column>
      <el-table-column
        prop="role_name"
        label="角色">
      </el-table-column>

      <el-table-column label="状态">

    <template slot-scope="scope">
      <el-switch
  v-model="scope.row.mg_state"
  active-color="#13ce66"
  inactive-color="#ff4949" @change="userStateChange(scope.row)">
    </el-switch>

    </template>
      </el-table-column>

      <el-table-column
        label="操作" width="200px">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="编辑" placement="top-start" :enterable="false">
               <el-button type="primary" icon="el-icon-edit" plain size="mini" @click="showEditDialog(scope)"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top-start" :enterable="false">
                         <el-button type="danger" icon="el-icon-delete" plain size="mini" @click="showDeleteDialog(scope)"></el-button>

          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="分配角色" placement="top-start" :enterable="false">
                         <el-button type="warning" icon="el-icon-setting" plain size="mini" @click="showSetRoleDialog(scope.row)"></el-button>
          </el-tooltip>

        </template>
      </el-table-column>
  </el-table>

  <el-pagination class="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1, 2,5, 10]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
  </el-pagination>
</el-card>

<el-dialog
  title="添加用户"
  :visible.sync="dialogVisible"
  width="70%" @close="addDialogClosed"
  >
  <!-- 输入用户信息的栏目 -->
  <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px" class="demo-ruleForm">
  <el-form-item label="用户名字" prop="username">
    <el-input v-model="addForm.username"></el-input>
  </el-form-item>

  <el-form-item label="用户密码" prop="password">
    <el-input v-model="addForm.password"></el-input>
  </el-form-item>

  <el-form-item label="邮箱" prop="email">
    <el-input v-model="addForm.email"></el-input>
  </el-form-item>

  <el-form-item label="手机" prop="mobile">
    <el-input v-model="addForm.mobile"></el-input>
  </el-form-item>
  </el-form>
<!-- 这是取消和确定的两个按钮 -->
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
</el-dialog>
<el-dialog
  title="修改用户的信息"
  :visible.sync="editDialogVisible"
  width="70%" @close="editDialogClosed"
  >
  <!-- 输入用户信息的栏目 -->
  <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="70px" class="demo-ruleForm">
  <el-form-item label="用户名" >
    <el-input v-model="editForm.username" disabled></el-input>
  </el-form-item>

  <el-form-item label="邮箱" prop="email">
    <el-input v-model="editForm.email"></el-input>
  </el-form-item>

  <el-form-item label="手机" prop="mobile">
    <el-input v-model="editForm.mobile"></el-input>
  </el-form-item>

  </el-form>
<!-- 这是取消和确定的两个按钮 -->
  <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUser">确 定</el-button>
  </span>
</el-dialog>


<el-dialog
  title="提示"
  :visible.sync="deleteDialogVisible"
  width="70%"
  >
  <!-- 输入用户信息的栏目 -->
  <em class="el-icon-warning"></em>此操作将永久删除该用户，是否继续？
<!-- 这是取消和确定的两个按钮 -->
  <span slot="footer" class="dialog-footer">
    <el-button @click="deleteDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="deleteUser">确 定</el-button>
  </span>
</el-dialog>

<el-dialog
  title="分配角色"
  :visible.sync="roleDialogVisable"
  width="70%"
  >
  <!-- 输入用户信息的栏目 -->
  <div>当前的用户:{{row.username}}</div>
  <div>当前的角色:{{row.role_name}}</div>
  <div>分配的新角色:
    <el-select v-model="selectedRoleId" placeholder="请选择">
      <el-option
      v-for="item in rolesList"
      :key="item.id"
      :label="item.roleName"
      :value="item.id" ref="elSelect">
      </el-option>
    </el-select>
  </div>
<!-- 这是取消和确定的两个按钮 -->
  <span slot="footer" class="dialog-footer">
    <el-button @click="roleDialogVisable = false">取 消</el-button>
    <el-button type="primary" @click="changeRole">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
export default {
  data(){
    // 验证邮箱的规则
    let checkEmail = (rule, value, cb) => {
        const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if(regEmail.test(value))
        return cb();
      cb(new Error("请输入合法的邮箱"));
      };

       // 验证邮箱的规则
     let checkMobile = (rule, value, cb) => {
        const regMobile =/^(0|86|17951)?(13[0-9]|15[123456789]|17[678|18[0-9]|14[57])[0-9]{8}$/;
      if(regMobile.test(value))
        return cb();
      cb(new Error("请输入合法的手机"))
      };

    return {
      queryInfo:{
        query:'',
        pagenum:1,
        pagesize:2,

      },
      userslist:[],
      total:0,
      valueForSwitch:true,
      dialogVisible:false,
      editDialogVisible:false,
      deleteDialogVisible:false,
      roleDialogVisable : false,
      deleteID:'',
      row:{},
      rolesList:[],
      selectedRoleId:'',
      addForm:{
        username:'',
        password:'',
        email:'',
        mobile:""
      },
      editForm:{
        id:'',
        email:'',
        mobile:'',
        username:''
      },
      addFormRules:{
        username:[{required:true, message:"请输入用户名",trigger:'blur'},
        {min:3,max:10,message:"用户名的长度在3到10之间",trigger:'blur'}],
        password:[{required:true, message:"请输入用户密码",trigger:'blur'},
        {min:6,max:15,message:"用户名的长度在6到15之间",trigger:'blur'}],

        email:[
          {required:true, message:"用户邮箱不能为空",trigger:'blur'},
          {validator:checkEmail, trigger:'blur'}
        ],

        mobile:[{required:true, message:"手机号码不能为空",trigger:'blur'},
        {validator:checkMobile, trigger:'blur'},
        ],

      }
    }
  },
  methods:{
    async getUserlist(){
      const {data:res} = await this.$http.get('users',{ params: this.queryInfo});
      this.userslist = res.data.users;
      this.total = res.data.total;
    },
    handleSizeChange(newSize){
      this.queryInfo.pagesize = newSize;
      this.getUserlist();
    },
    handleCurrentChange(newPage){
      this.queryInfo.pagenum = newPage;
      this.getUserlist();
    },
    async userStateChange(userInfo){
      console.log(userInfo);
      const {data:res} = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`);
      if(res.meta.status != 200){
        userInfo.mg_state = !userInfo.mg_state;
        return this.$message.error("修改用户状态失败")
}
      return this.$message.success("修改用户状态成功");
    },
    sayHi(){
      console.log("Hello from the sayHi function!")
    },
    addDialogClosed(){
      this.$refs.addFormRef.resetFields();
    },
     addUser(){
      this.$refs.addFormRef.validate(async valid => {
        if(!valid) return;
        const {data:res } = await this.$http.post('users',this.addForm);
        if(res.meta.status!=201)
          return this.$message.error("添加用户失败");
        this.$message.success("添加用户成功");
        this.dialogVisible = false;
        this.getUserlist();
      })
    },
    async showEditDialog(scope){
      this.editDialogVisible = true;
      const {data:res} = await this.$http.get(`users/${scope.row.id}`);
      this.editForm.id = res.data.id;
      this.editForm.email = res.data.email;
      this.editForm.mobile = res.data.mobile;
      this.editForm.username = res.data.username;


    },
    async showDeleteDialog(scope){
      this.deleteDialogVisible = true;
      this.deleteID = scope.row.id;

    },
    editUser(){
      this.$refs.editFormRef.validate(async valid => {

        if(!valid) return;
        const {data:res} = await this.$http.put(`users/${this.editForm.id}`,this.editForm);
        if(res.meta.status!=200)
          return this.$message.error("修改用户失败");
        this.$message.success("修改用户成功");
        this.editDialogVisible = false;
        this.getUserlist();
      })
    },
    editDialogClosed(){
      this.$refs.editFormRef.resetFields();
    },
    async deleteUser(){
      const {data:res} = await this.$http.delete(`users/${this.deleteID}`);
      if(res.meta.status != 200)
      {
        return this.$message.error("删除用户失败");

      }
      this.$message.success("删除用户成功")
      this.deleteDialogVisible = false;
      this.getUserlist();
      console.log("程序执行到了删除的最后一步")
    },
    async showSetRoleDialog(scope){
      this.selectedRoleId = '';
      this.row = scope;
      this.roleDialogVisable = true;
      const {data:res} = await this.$http.get('/roles');
      if(res.meta.status != 200) {
        return this.$message.error("获取角色列表失败");
      }
      this.$message.success("获取角色列表成功");
      this.rolesList = res.data;
    },
    async changeRole(){
      console.log(this.selectedRoleId);
      if(!this.selectedRoleId) return this.$message.error('请选择角色！');
      const {data:res} = await this.$http.put(`users/${this.row.id}/role`,{rid:this.selectedRoleId});
      if(res.meta.status != 200){
        return this.$message.error("设置角色失败！")
      }
      this.$message.success("设置角色成功");
      this.getUserlist();
      this.roleDialogVisable = false;

    }


  },
   created(){
    this.getUserlist();
  },

}


</script>

<style scoped>
  .box-card{
    margin-top: 10px;
    box-shadow: 0 1px 2px rgba(0, 0,0,0.2) !important;
  }
.searchBar{
  width: 50%;
  margin-right: 20px;
}
.addBut{
  width: 20%;
}

.el-table{
  margin-top:20px;
  font-size: 10px;

}
.pagination{
  margin-top:15px;
}
.el-icon-warning{
color:yellow
}
</style>
